package com.matrixlearning.controller;

import com.matrixlearning.mapper.SignMapper;
import com.matrixlearning.mapper.UserMapper;
import com.matrixlearning.pojo.Sign;
import com.matrixlearning.pojo.User;
import com.matrixlearning.utils.GsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/index")
public class IndexController {
    /**
     * Auther sun
     * DATE 2023/2/18 22:45
     * VERSION 1.0
     */

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SignMapper signMapper;

    /**
     * 签到
     * @param token
     * @return
     */
    @PostMapping("/sign")
    public String sign(@RequestBody String token) {
        String userJson = (String) redisTemplate.opsForValue().get("user:" + token);
        User user = GsonUtils.fromJson(userJson, User.class);
        Sign sign = signMapper.selectById(user.getId());
        if(sign.getFlag() == 1) {
            return "already";
        }
        if(sign.getNumber()>=100) {
            return "error";
        }
        if(sign.getNumber()>=90) {
            Integer newNumber =  sign.getNumber() + 1;
            sign.setNumber(newNumber);
            signMapper.updateById(sign);
            return "good";
        }
        Integer newNumber = sign.getNumber() + 1;
        sign.setNumber(newNumber);
        signMapper.updateById(sign);
        return "success";
    }

    @PostMapping("/getSignNumber")
    public String getSignNumber(@RequestBody String token) {
        String userJson = (String) redisTemplate.opsForValue().get("user:" + token);
        User user = GsonUtils.fromJson(userJson, User.class);
        Sign sign = signMapper.selectById(user.getId());
        Integer number = sign.getNumber();


        return "" + number;
    }
}
